﻿#include "tcpthread.h"
#include "../../include/macro.h"

TCPThread::TCPThread(uint _id, int _ip)
    :ip(_ip), id(_id)
{
    moveToThread(this);
}

TCPThread::~TCPThread()
{
    m_timer->stop();
    tcpSocket->disconnectFromHost();
    tcpSocket->close();
    delete tcpSocket;
    delete m_timer;
}

void TCPThread::run()
{
    qDebug() << "dtu:"<< ip <<" tcp "<<QThread::currentThreadId();
    cmdSend.resize(8);
    /*
    cmdSend[0] = 0x01;
    cmdSend[1] = 0x04;
    cmdSend[2] = 0x00;
    cmdSend[3] = 0x0A;
    cmdSend[4] = 0x00;
    cmdSend[5] = 0x10;
    cmdSend[6] = 0xD1;
    cmdSend[7] = 0xC4;
    */
    tcpSocket = new QTcpSocket();
    tcpSocket->setParent(0);
    if(id == 31)
        tcpSocket->connectToHost(TO_STR(HOST_IP), HOST_PORT);
    else
        tcpSocket->connectToHost(TO_STR(HOST_IP),7880);
    if(!tcpSocket->waitForConnected(TCP_CONNECT_WAIT))
    {
        qDebug() <<"dtu:"<< ip <<  " tcp connection fail"<<endl;
    }
    else
    {
        qDebug() <<"dtu:"<< ip <<  " tcp connected"<<endl;
        connect(tcpSocket, &QTcpSocket::readyRead, this, &TCPThread::slt_readData, Qt::QueuedConnection);

        m_timer = new QTimer();
        m_timer->setTimerType(Qt::PreciseTimer);
        m_timer->setInterval(DTU_INTERVAL);
        connect(m_timer, &QTimer::timeout, this, &TCPThread::slt_handleTimeout, Qt::QueuedConnection);
        m_timer->start();
    }
    exec();
}

void TCPThread::slt_readData()
{
    cnt_line++;
    //cnt_table++;


    const QByteArray data = tcpSocket->read(324);
/*
    qDebug() << "start_pack";
    for(int i=0;i<324;i++)
        qDebug()<<i<<" "<<(data.at(i) & 0x000000FF);
    qDebug() << "end_pack";
    */
/*
        begin = clock();
*/
    QList<int>datalist;
    for(int i = 2;i < 322;i+=32)
        for(int j=0;j<8;j+= 2)
            datalist.push_back((data.at(i+j) & 0x0000FF00) | (data.at(i+j+1) & 0x000000FF));

    emit sig_dtuUpload(id, datalist);

    if(cnt_line == DTU_DISPLAY_LINE_N)
    {
        QList<int>dat{datalist[0],datalist[1],datalist[2],datalist[3]};
        //qDebug()<< dat[0]<<" "<<dat[1]<<" "<<dat[2]<<" "<<dat[3];

        emit sig_dtuUpdate(id, dat);
        cnt_line = 0;
    }
    /*
    end = clock();
    qDebug() << end - begin<<endl;
*/
}

void TCPThread::slt_handleTimeout()
{
    tcpSocket->write(cmdSend);
}



